import 'dart:convert';
import 'dart:io';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/ecycommon/EcyEventBus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../constant/color_constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../constant/constant.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyEncrptyUtil.dart';
import '../../ecycommon/utils/EcyJPushUtil.dart';
import '../../ecycommon/utils/EcyRegUtil.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';
import 'common/PasswordFormatter.dart';
import 'common/CustomTextFieldWidget.dart';

class EcyPasswordLoginPage extends EcyCommonBaseWidget {
  final String targetUrl;
  final dynamic targetParam;

  EcyPasswordLoginPage(this.targetUrl, this.targetParam);

  @override
  _EcyPasswordLoginPageState createState() {
    return _EcyPasswordLoginPageState(this, targetUrl, targetParam);
  }
}

class _EcyPasswordLoginPageState extends EcyCommonBaseWidgetState
    with SingleTickerProviderStateMixin {
  String mobile = "";
  String pwd = "";
  bool pwdShowFlag = true;
  bool loadingFlag = false;
  bool checked = false;
  bool canNext = false;
  int left = 60;
  final String targetUrl; //为空为普通登陆，需要直接返回；有值表示需要登陆后跳往下级页面
  final dynamic targetParam;

  late EcyCommonBaseWidget controller;
  late AnimationController _controller;

  _EcyPasswordLoginPageState(EcyCommonBaseWidget vc, this.targetUrl, this.targetParam) {
    controller = vc;
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(); // 无限循环
  }

  //private
  void onUpdateMobile(String newValue) {
    setState(() {
      mobile = newValue;
      if (mobile.length == 11 && pwd.isNotEmpty) {
        canNext = true;
      } else {
        canNext = false;
      }
    });
  }

  void onUpdatePwd(String newValue) {
    setState(() {
      pwd = newValue;
      if (mobile.length == 11 && pwd.isNotEmpty) {
        canNext = true;
      } else {
        canNext = false;
      }
    });
  }

  void autoLogin() async {
    if (loadingFlag) {
      return;
    }

    _loading();
    Map<String, dynamic> body = {};
    body["username"] = mobile;
    body["password"] = EcyEncrptyUtil.aesEncode(pwd);
    body["loginType"] = "0";
    body["pushId"] = await EcyJPushUtil.getRegistrationID();
    body["clientType"] = Platform.isAndroid ? 0 : 1;
    try {
      var response =
          await EcyRequestbasemanager().post("/app/api/app/user/login", body);
      if (response != null) {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          if (resp.code == 0 || resp.code == 200) {
            EcyUserModel user = EcyUserModel.fromJson(response["data"]);
            EcyUserUtil.saveLoginedData(user); //缓存登陆信息
            //发送全局通知
            EcyEventBus().emit(EcyEventConst.kLogined);
            if (targetUrl.isNotEmpty) {
              EcyRouter.popAndPushNamed(context, targetUrl, targetParam);
            } else {
              EcyRouter.pop(context, "");
            }
          } else {
            EasyLoading.showToast(resp.msg ?? "登录失败",
                duration: const Duration(seconds: 2));
          }
        } else {
          EasyLoading.showToast(resp.msg ?? "登录失败",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast(Constant.NET_ERROR);
    } finally {
      setState(() {
        loadingFlag = false;
      });
    }
  }

  _loading() {
    setState(() {
      loadingFlag = true;
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: ColorConstant.White,
      appBar: AppBar(
        toolbarHeight: 40.h,
        backgroundColor: ColorConstant.White,
        title: Text(title),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          //触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              height: 50.h,
            ),
            Image(
                image: const AssetImage('assets/images/login_app_icon.png'),
                width: 80.w,
                height: 80.w),
            SizedBox(width: MediaQuery.of(context).size.width, height: 45.h),
            Wrap(
              alignment: WrapAlignment.center,
              direction: Axis.horizontal,
              crossAxisAlignment: WrapCrossAlignment.center,
              spacing: 0,
              children: [
                Image(
                    image:
                        const AssetImage('assets/images/ic_login_account.png'),
                    width: 24.w,
                    height: 24.w),
                SizedBox(
                  width: MediaQuery.of(context).size.width - 60.w,
                  height: 36.h,
                  child: CustomTextFieldWidget(
                    hint: "请输入手机号",
                    inputValue: mobile,
                    updateMessageCallback2: onUpdateMobile,
                    textInputFormatterList: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(11)
                    ],
                    keyboardType: TextInputType.phone,
                    obscureText: false,
                  ),
                )
              ],
            ),
            Container(
              margin: EdgeInsets.only(left: 0, right: 0, top: 10.h, bottom: 0),
              height: 0.5.h,
              width: MediaQuery.of(context).size.width - 40.w,
              decoration: BoxDecoration(
                color: Colors.grey.shade500,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 0, right: 0, top: 25.h, bottom: 0),
              child: Wrap(
                alignment: WrapAlignment.center,
                direction: Axis.horizontal,
                crossAxisAlignment: WrapCrossAlignment.center,
                spacing: 0,
                children: [
                  Image(
                      image: const AssetImage('assets/images/ic_login_pwd.png'),
                      width: 24.w,
                      height: 24.w),
                  SizedBox(
                    width: MediaQuery.of(context).size.width - 80.w,
                    height: 36.h,
                    child: CustomTextFieldWidget(
                      hint: "请输入6位及以上密码",
                      inputValue: pwd,
                      updateMessageCallback2: onUpdatePwd,
                      textInputFormatterList: [
                        PasswordFormatter(),
                        LengthLimitingTextInputFormatter(50)
                      ],
                      keyboardType: TextInputType.text,
                      obscureText: pwdShowFlag,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        pwdShowFlag = !pwdShowFlag;
                      });
                    },
                    child: Icon(
                      pwdShowFlag
                          ? CupertinoIcons.eye
                          : CupertinoIcons.eye_slash,
                      size: 18,
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 0, right: 0, top: 10.h, bottom: 0),
              height: 0.5.h,
              width: MediaQuery.of(context).size.width - 40.w,
              decoration: BoxDecoration(
                color: Colors.grey.shade500,
              ),
            ),
            Container(
                width: MediaQuery.of(context).size.width,
                margin: const EdgeInsets.only(
                    left: 20, right: 20, top: 20, bottom: 10.0),
                child: Wrap(
                  alignment: WrapAlignment.spaceBetween,
                  direction: Axis.horizontal,
                  // alignment: WrapAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                        child: Text("忘记密码",
                            textAlign: TextAlign.start,
                            style: TextStyle(
                                fontFamily: "PingFag SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: ColorConstant.CommonColor)),
                        onTap: () {
                          EcyRouter.pushNoParams(
                              context, EcyRouter.resetPasswordPage);
                        }),
                    SizedBox(width: 10.w, height: 20.w),
                    Wrap(
                      alignment: WrapAlignment.spaceBetween,
                      direction: Axis.horizontal,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      // alignment: WrapAlignment.spaceBetween,
                      children: [
                        Text("还没有账号?",
                            textAlign: TextAlign.start,
                            style: TextStyle(
                                fontFamily: "PingFag SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: ColorConstant.CommonColorGray)),
                        SizedBox(width: 10.w, height: 20.w),
                        GestureDetector(
                          onTap: () {
                            EcyRouter.pushNoParams(
                                context, EcyRouter.registerLoginPage);
                          },
                          child: Text(
                            "去注册",
                            textAlign: TextAlign.start,
                            style: TextStyle(
                                fontFamily: "PingFag SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: ColorConstant.CommonColor),
                          ),
                        ),
                      ],
                    )
                  ],
                )),
            GestureDetector(
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  if (!EcyRegUtil.validTel(mobile)) {
                    EasyLoading.showToast("请输入11位合法手机号",
                        duration: const Duration(seconds: 2));
                    return;
                  }
                  if (pwd.length < 6) {
                    EasyLoading.showToast("密码长度最小6位",
                        duration: const Duration(seconds: 1));
                    return;
                  }
                  if (!checked) {
                    EasyLoading.showToast("请先勾选协议",
                        toastPosition: EasyLoadingToastPosition.center,
                        duration: const Duration(seconds: 2));
                    return;
                  }
                  autoLogin();
                },
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(26.r),
                    color: ColorConstant.CommonColor,
                  ),
                  margin: EdgeInsets.only(
                      left: 22.w, right: 22.w, top: 35.h, bottom: 10.h),
                  width: MediaQuery.of(context).size.width - 44.w,
                  height: 52.h,
                  alignment: Alignment.center,
                  child: Stack(children: [
                    SizedBox(
                      height: 45.h,
                      width: 45.w,
                      child: Align(
                        alignment: Alignment.center,
                        child: Transform.translate(
                          offset: const Offset(-35.0, 0.0),
                          child: loadingFlag
                              ? Image.asset(
                              width: 28.w,
                              height: 25.h,
                              alignment: Alignment.center,
                              "assets/images/loading/loading.gif")
                              : null,
                        ),
                      ),
                    ),
                    SizedBox(
                        height: 45.h,
                        width: 45.w,
                        child: Align(
                          alignment: Alignment.center,
                          child: Text('登录',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w500,
                                  fontSize: 18.sp,
                                  color: ColorConstant.White)),
                        )),
                  ]),
                )),
            const Padding(padding: EdgeInsets.only(top: 20)),
            GestureDetector(
              onTap: () {
                EcyRouter.pushNoParams(
                    context, EcyRouter.verificationCodeLoginPage);
              },
              child: Text("其他方式登录",
                  textAlign: TextAlign.start,
                  style: TextStyle(
                      fontFamily: "PingFag SC",
                      fontWeight: FontWeight.w400,
                      fontSize: 16.sp,
                      color: ColorConstant.CommonColor)),
            ),
            Expanded(
              child: Container(
                color: Colors.transparent,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Wrap(
                direction: Axis.horizontal,
                spacing: 0,
                children: [
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () => {
                      setState(() {
                        checked = !checked;
                      }),
                    },
                    child: Image(
                        image: AssetImage(checked
                            ? 'assets/images/login_checked.png'
                            : 'assets/images/login_unchecked.png'),
                        width: 22.w,
                        height: 22.w),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width - 40.w,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {},
                      child: Padding(
                        padding: const EdgeInsets.only(top: 3),
                        child: RichText(
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: ' 已详细阅读并同意',
                                style: TextStyle(
                                    color: const Color.fromARGB(
                                        255, 140, 140, 140),
                                    fontSize: 12.sp),
                              ),
                              TextSpan(
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      EcyRouter.pushNoParams(
                                          context, EcyRouter.privacyPolicyPage);
                                    },
                                  text: '《使用条款和个人信息保护政策》',
                                  style: TextStyle(
                                      color: ColorConstant.CommonColor,
                                      fontSize: 12.sp)),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: MediaQuery.of(context).size.width, height: 40.h),
          ],
        ),
      ),
    );
  }
}
